import React, { Component } from 'react'
import { getGoodCategory } from "../../data/api"
import styles from "./category.module.scss"
import BrNav from "../brNav/BrNav"
import SearchInput from "../searchInput/SearchInput"
import {withRouter} from "react-router-dom"
class Category extends Component {
  state = {
    categories: [],//分类数据
    select_index: 0,//当前选中的分类
    rightContent: [],//右边内容数据
  }
  async componentDidMount() {
    let res = await getGoodCategory();
    // console.log(res);
    let message = res.message || [];
    this.setState({
      categories: message,
      rightContent: message[0]
    })
  }
  handleItemClick = (e) => {
    //自定义的属性存放在 e.target.dataset 中
    // console.log(e.target.dataset.index);
    let index = parseInt(e.target.dataset.index);
    this.setState({
      select_index: index,
      rightContent: this.state.categories[index]
    })
  }
  //点击商品图标跳转到商品列表
  productItemClick = (cid) => {
    this.props.history.push("goodList?cid="+cid);
  }
  render() {
    return <div className={styles.category}>
      <BrNav title="商品分类" left={false}></BrNav>
      <SearchInput></SearchInput>
      <div className={styles.categoryContent}>
        <div className={styles.categoryContentLeft} onClick={this.handleItemClick}>
          {
            this.state.categories.map((v, index) => {
              return <div className={this.state.select_index === index ? `${styles.active} ${styles.contentLeftItem}` : styles.contentLeftItem}
                key={v.cat_id}
                data-index={index}
                data-list={index}
              >
                {v.cat_name}
              </div>
            })
          }
        </div>
        <div className={styles.categoryContentRight}>
          {
            this.state.rightContent.children && this.state.rightContent.children.map((item, index) => {
              return <div className={styles.contentRightItem} key={item.cat_id}>
                <div className={styles.itemTitle}>/{item.cat_name}/</div>
                <div className={styles.productList}>
                  {
                    item.children && item.children.map((v, i) => {
                      return <div className={styles.productItem} key={v.cat_id} onClick={this.productItemClick.bind(this,v.cat_id)}>
                        <div className={styles.imgWrapper}>
                          <img src={v.cat_icon} alt="" />
                        </div>
                        <div className={styles.title}>
                          {v.cat_name}
                        </div>
                      </div>
                    })
                  }
                </div>
              </div>
            })
          }
        </div>
      </div>
    </div>
  }
}
export default withRouter(Category)